import AuthUtil from '../../common/AuthUtils';
import StorageUtil from '../../utils/StorageUtil';
import {Constant} from '../../common/Constant';
import NavigationUtil from '../../navigators/NavigationUtil';
import Utils from '../../utils/Utils';
import {BASE_URL} from '../../common/BASE_URL';

export default class HttpUtils {
  //先定义延时函数
  static delay = () => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject(new Error('网络超时'));
      }, 100);
    });
  };

  static pingIp = (url, data) => {
    return Promise.race([
      new Promise((resolve, reject) => {
        AuthUtil.getAuthParam()
          .then((authHeader) => {
            fetch(url, {
              headers: {
                'Content-Type': 'application/json',
                ...authHeader,
              },
              method: 'GET',
              timeout: 100,
              body: JSON.stringify(data),
            }) //默认是GET
              .then((response) => {
                if (response.ok) {
                  return response.json();
                }
                throw new Error('Network response was not ok.');
              })
              .then((result) => {
                resolve(result); //表示完成
              })
              .catch((error) => {
                reject(error); //表示失败
              });
          })
          .catch((error) => {
            reject(error);
          });
      }),
      this.delay(),
    ]);
  };
  /**
   * query :{
   *   url: '',
   *   type: '',
   *   data: ''
   * }
   */
  static request = (query) => {
    let url = query.url;
    const params = query.params;
    if (params) {
      let q = '?';
      for (let item in params) {
        q += `${item}=${params[item]}&`;
      }
      url += q.substring(0, q.length - 1);
    }
    let header=query.header?query.header:null
    // const repeatLogin = async ()=>{
    //   const username = await StorageUtil.get('local_username');
    //   const password = await StorageUtil.get('local_password');
    //   const str = 'deviceId=' + Utils.getRandomString() + '&username=' + username + '&password=' + password;
    //   const url = BASE_URL.apoLoginUrl + '/user/token?' + str;
    //   fetch(url, {
    //     headers: {
    //       'Content-Type': 'application/x-www-form-urlencoded',
    //       Authorization: 'Basic YXBwOmFwcA==',
    //     },
    //     method: 'POST',
    //   })
    //     .then(function (response) {
    //       return response.json();
    //     })
    //     .then((result) => {
    //       if (result && result.code === 0) {
    //         const {token_type, access_token} = result.data;
    //         // 缓存TOKEN
    //         StorageUtil.save(Constant.token, token_type + ' ' + access_token);
    //       } else {
    //       }
    //     })
    //     .catch((e) => {
    //       this.refs.toast.show('网络异常，请检查网络连接');
    //     });
    // }

    return new Promise((resolve, reject) => {
      AuthUtil.getAuthParam()
        .then((authHeader) => {
          fetch(url, {
            headers: {
              'Content-Type':header?header:'application/json',
              ...authHeader,
            },
            method: query.type || 'GET',
            body: query.data && JSON.stringify(query.data),
          }) //默认是GET
            .then((response) => {
              return response.json();
            })
            .then((result) => {
              if (
                result.status == 401 &&
                (
                  result.message.indexOf('Invalid access token') !== -1 ||
                  result.message.indexOf('Full authentication') !== -1
                )
              ) {
                StorageUtil.delete(Constant.token);
                NavigationUtil.goPage('Login', {
                  isInvalid: true,
                });
                // this.repeatLogin()
              } else {
                resolve(result); //表示完成
              }
            })
            .catch((error) => {
              reject(error); //表示失败
            });
        })
        .catch((error) => {
          reject(error);
        });
    });
  };

  static get = (url, data) => {
    return new Promise((resolve, reject) => {
      AuthUtil.getAuthParam()
        .then((authHeader) => {
          fetch(url, {
            headers: {
              'Content-Type': 'application/json',
              ...authHeader,
            },
            method: 'GET',
            body: data && JSON.stringify(data),
          }) //默认是GET
            .then((response) => {
              if (response.ok) {
                return response.json();
              }
              throw new Error('Network response was not ok.');
            })
            .then((result) => {
              resolve(result); //表示完成
            })
            .catch((error) => {
              reject(error); //表示失败
            });
        })
        .catch((error) => {
          reject(error);
        });
    });
  };
  static post = (url, data) => {
    return new Promise((resolve, reject) => {
      AuthUtil.getAuthParam()
        .then((authHeader) => {
          if (authHeader) {
            fetch(url, {
              headers: {
                'Content-Type': 'application/json',
                ...authHeader,
              },
              method: 'POST',
              body: JSON.stringify(data),
            }) //返回 服务器处理的结果
              .then((response) => {
                if (response.ok) {
                  return response.json();
                }
                throw new Error('Network response was not ok.');
              })
              .then((result) => {
                resolve(result);
              })
              .catch((error) => {
                reject(error);
              });
          } else {
            reject('no user auth');
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  };
  static urlGet = (url, data) => {
    return new Promise((resolve, reject) => {
      AuthUtil.getAuthParam()
        .then((authHeader) => {
          if (authHeader) {
            let netUrl = url;
            if (url.indexOf('?') !== -1) {
              netUrl = url + '&tenantId=' + authHeader.tenantId;
            } else {
              netUrl = url + '?tenantId=' + authHeader.tenantId;
            }
            fetch(netUrl, {
              headers: {
                'Content-Type': 'application/json',
              },
              method: 'get',
              body: JSON.stringify(data),
            }) //返回 服务器处理的结果
              .then((response) => {
                if (response.ok) {
                  return response.json();
                }
                throw new Error('Network response was not ok.');
              })
              .then((result) => {
                resolve(result);
              })
              .catch((error) => {
                reject(error);
              });
          } else {
            reject('no user auth');
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  };

  static urlPost = (url, data) => {
    return new Promise((resolve, reject) => {
      AuthUtil.getAuthParam()
        .then((authHeader) => {
          if (authHeader) {
            let netUrl = url;
            if (url.indexOf('?') !== -1) {
              netUrl =
                url +
                '&tenantId=' +
                authHeader.tenantId +
                '&userId=' +
                authHeader.userId;
            } else {
              netUrl =
                url +
                '?tenantId=' +
                authHeader.tenantId +
                '&userId=' +
                authHeader.userId;
            }
            fetch(netUrl, {
              headers: {
                'Content-Type': 'application/json',
              },
              method: 'POST',
              body: JSON.stringify(data),
            }) //返回 服务器处理的结果
              .then((response) => {
                if (response.ok) {
                  return response.json();
                }
                throw new Error('Network response was not ok.');
              })
              .then((result) => {
                resolve(result);
              })
              .catch((error) => {
                reject(error);
              });
          } else {
            reject('no user auth');
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  };
  static formPost = (url, data) => {
    const params = [];
    for (let key in data) {
      // params.append(key,data[key])
      params.push(
        encodeURIComponent(key) + '=' + encodeURIComponent(data[key]),
      );
    }
    return new Promise((resolve, reject) => {
      AuthUtil.getAuthParam()
        .then((authHeader) => {
          if (authHeader) {
            fetch(url, {
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                ...authHeader,
              },
              method: 'POST',
              body: params.length > 0 ? params.join('&') : '',
            }) //返回 服务器处理的结果
              .then((response) => {
                if (response.ok) {
                  return response.json();
                }
                throw new Error('Network response was not ok.');
              })
              .then((result) => {
                resolve(result);
              })
              .catch((error) => {
                reject(error);
              });
          } else {
            reject('no user auth');
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  };

  static async repeatLogin() {
    const username = await StorageUtil.get('local_username');
    const password = await StorageUtil.get('local_password');
    const str =
      'deviceId=' +
      Utils.getRandomString() +
      '&username=' +
      username +
      '&password=' +
      password;
    const url = BASE_URL.apoLoginUrl + '/user/token?' + str;
    fetch(url, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: 'Basic YXBwOmFwcA==',
      },
      method: 'POST',
    })
      .then(function (response) {
        return response.json();
      })
      .then((result) => {
        if (result && result.code === 0) {
          const {token_type, access_token} = result.data;
          // 缓存TOKEN
          StorageUtil.save(Constant.token, token_type + ' ' + access_token);
          NavigationUtil.goPage('Main', {
            isInvalid: true,
          });
        } else {
          StorageUtil.delete(Constant.token);
          NavigationUtil.goPage('Init', {
            isInvalid: true,
          });
        }
      })
      .catch((e) => {
        StorageUtil.delete(Constant.token);
        NavigationUtil.goPage('Init', {
          isInvalid: true,
        });
      });
  }
}
